/**  
 * 文件名:    IVRHandler.java  
 * 描述:   
 * 作者:     Sue
 * 版本:    1.0  
 * 创建时间:   2014-12-3 下午05:04:26  
 *  
 * 修改历史:  
 * 日期                          作者           版本         描述  
 * ------------------------------------------------------------------  
 * 2014-12-3      Sue      1.0        1.0 Version  
 */ 
package com.hp.bon.sgw.wh.channel.handler;

import java.io.PrintStream;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.hp.bon.sgw.Constants;
import com.hp.bon.sgw.Constants.MessageType;
import com.hp.bon.sgw.bean.XmlMessage;
import com.hp.bon.sgw.core.BuzProcessorManager;
import com.hp.bon.sgw.core.CallParam;
import com.hp.bon.sgw.core.channel.SoapChannel;
import com.hp.bon.sgw.core.channel.handler.IAsynCallHandler;
import com.hp.bon.sgw.domain.MessageDetail;
import com.hp.bon.sgw.threads.MessageDetailCacheManager;
import com.hp.bon.sgw.threads.TaskManager;
import com.hp.ocs.diameter.message.Message;

/**  
 * @ClassName: IVRHandler   
 * @Description: IVRHandler  
 * @author: Sue  
 * @date:2014-12-3 下午05:04:26     
 */
public class IVRHandler implements IAsynCallHandler
{
	
	private static final Logger logger = LoggerFactory.getLogger(IVRHandler.class);
	
	private static final String PREFIX_LABEL = "<Service_Information>";
	private static final String SUFFIX_LABEL = "</Service_Information>";
	private PrintStream printStream;
	
	public IVRHandler(PrintStream printStream)
	{
		this.printStream = printStream;
	}

	@Override
	public void onCallResult(CallParam callParam) 
	{
		XmlMessage ack = null;
		Object response = null;

		if (callParam.getResponse() != null) 
		{
			response = callParam.getResponse();
		} 
		else if (callParam.getRecvResponse() != null) 
		{
			response = callParam.getRecvResponse();
		}

		if (response == null) 
		{
			ack = SoapChannel.createERRAnwser(callParam.getSessionId(),
			callParam.getRetCode() == 3002 ? 11202 : callParam.getRetCode(), callParam.getResultMsg());
		} 
		else 
		{
			if (response instanceof Message) 
			{
				ack = BuzProcessorManager.getInstance().convertMessageToAck(callParam);// CCA -> XML
			} 
			else if (response instanceof XmlMessage) 
			{
				ack = (XmlMessage) response;
			} 
			else 
			{
				logger.warn("unknown response type:"+ callParam.getResponse().getClass().getName());
			}
		}
		try 
		{
			String respXML = directIVRResponse(ack);
			byte[] resp = respXML.getBytes("UTF-8");
			ack.setLength(resp.length);
			ack.setMsgTime(System.currentTimeMillis());
			printStream.write(resp);
			printStream.close();

			callParam.setResponse(ack);

			if (callParam.getRetCode() == Constants.ResultCode.SUCCESS) // 成功的消息，请求应答入库
			{
				MessageDetail detail = new MessageDetail();
				detail.setBusinessCallId(callParam.getBussinessCallId());
				detail.setSessionId(callParam.getSessionId());
				detail.setServiceContextId(callParam.getServiceContextId());
				detail.setMessageType(MessageType.WSA);
				detail.setDetails(ack.getDATA());
				detail.setMsgTime(new Date(ack.getMsgTime()));
				detail.setOpType("send");
				detail.setHostId(callParam.getUserName());
				MessageDetailCacheManager.getInstance().add(detail);
			}

			TaskManager.taskProcess(callParam);
			if (logger.isInfoEnabled()) 
			{
				logger.info("http response to IVR : " + respXML);
			}
		} 
		catch (Exception e) 
		{
			logger.info("Exception is :"+e);
		}
	}
	
	/**
	 * 
	 * @MethodName: directIVRResponse   
	 * @Description: IVR Response  
	 * @param @param ack
	 * @param @return  
	 * @return String  
	 * @throws
	 */
	protected String directIVRResponse(XmlMessage ack) {
		
		String dataInfo = "";
		StringBuilder sb = new StringBuilder();
		
		String orinData = ack.getDATA();
		if (orinData != null) 
		{
			dataInfo = orinData.substring(orinData.indexOf(PREFIX_LABEL)+PREFIX_LABEL.length(), orinData.indexOf(SUFFIX_LABEL));
		}
		
		sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>")
				.append("SERVICE")
				.append("<MID>").append(ack.getMID()).append("</MID>")
				.append("<RC>").append(ack.getRC()).append("</RC>")
				.append(dataInfo)
				.append("</SERVICE>");
		
		return sb.toString();
	}
	
	@Override
	public int getProtocolType() 
	{
		return 0;
	}
	
	public static void main(String[] args) {
		String s = "<DATA><![CDATA[   <Service_Information> <Result>0</Result> <Bill_Query_Information>  <AcctID>32100372402</AcctID>  " +
				"<Acct_Name>潘磊</Acct_Name>     <Due>0</Due>  <Derate_Due>0</Derate_Due>   <Valid_Balance>0</Valid_Balance><Should_Charge>0</Should_Charge>" +
				"<Previous_Change>0</Previous_Change><Current_Change>0</Current_Change></Bill_Query_Information></Service_Information>]]></DATA>";
		String a = s.substring(s.indexOf("<Service_Information>")
				+ "<Service_Information>".length(), s
				.indexOf("</Service_Information>"));
		System.out.println(a);
		System.out.println(s);
	}
}